package JDBC;

import com.mysql.cj.jdbc.MysqlDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 87111
 * Date: 2025-10-24
 * Time: 16:48
 */
public class demo2 {
    public static void main(String[] args) throws SQLException {
        //1. 创建数据源
        DataSource dataSource = new MysqlDataSource();
        ((MysqlDataSource)dataSource).setUrl("jdbc:mysql://127.0.0.1:3306/java1024?characterEncoding=utf8&useSSL=false");
        ((MysqlDataSource)dataSource).setUser("root");
        ((MysqlDataSource)dataSource).setPassword("123456");

        //2. 与数据库建立连接
        Connection connection = dataSource.getConnection();

        //3. 创建SQL语句
        String sql = "select * from student;";
        PreparedStatement statement = connection.prepareStatement(sql);

        //4. 向数据库发送语句执行
        ResultSet resultSet = statement.executeQuery();
        //遍历结果集
        while(resultSet.next()) {
            int id = resultSet.getInt("id");
            String name = resultSet.getString("name");
            System.out.println("id= " + id + " " + "name= " + name);
        }

        //5.释放资源
        resultSet.close();
        statement.close();
        connection.close();
    }
}
